package com.tanhua.server.service;

import com.tanhua.domain.mongo.Video;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author anshuai
 * @create 2021-02-26 16:07
 */
@Slf4j
@Service
public class VideoMQService {

    @Reference
    private VideoApi videoApi;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发布视频了，发送消息
     */
    public void saveVideoMessage(String videoId){
        sendMessage(videoId, 1);
    }

    /**
     * 点赞视频了，发送消息
     */
    public void likeVideoMessage(String videoId){
        sendMessage(videoId, 2);
    }

    /**
     * 取消点赞视频了，发送消息
     */
    public void unlikeVideoMessage(String videoId){
        sendMessage(videoId, 3);
    }

    /**
     * 评论视频了，发送消息
     */
    public void commentVideoMessage(String videoId){
        sendMessage(videoId, 4);
    }

    /**
     * 发送消息
     *
     * @param videoId 视频id
     * @param type    操作类型
     *                1发布视频，2点赞， 3取消点赞，4评论
     */
    public void sendMessage(String videoId, Integer type) {
        //根据videoId查询视频对象
        Video video = videoApi.findById(videoId);

        //构造消息对象
        Map<String, Object> message = new HashMap<>();
        message.put("userId", UserHolder.getUserId());
        message.put("videoId", video.getVid());
        message.put("type", type);

        //发送消息
        rocketMQTemplate.convertAndSend("tanhua-video", message);
        log.info("发送视频消息,供大数据推荐系统使用, topic:{}, message:{}", "tanhua-video", message);
    }
}
